package club.dmyang.common.shiro;

import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Created by brss on 2018/7/12.
 */
@Configuration
public class ShiroConfig {
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager securityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        /**
         * Shiro 内置过滤器，可以实现权限相关的拦截器
         * 常用的过滤器
         *  anon : 无需认证（登录）可以访问
         *  authc : 必须认证才可以访问
         *  user : 如果使用rememberme的功能可以直接访问
         *  perms : 该资源必须得到资源权限才可以访问
         *  role : 该资源必须得到角色权限才可以访问
         */

        // LinkedHashMap可以保证先后顺序
        Map<String,String> filterMap = new LinkedHashMap<String, String>();
        //放过登录接口和获取验证码的接口
        filterMap.put("/login","anon");
        filterMap.put("/vericode", "anon");
        filterMap.put("/plugins/**","anon");//静态资源
        //所有上面规则没匹配到的页面都需要认证才能访问
        filterMap.put("/*", "authc");
        filterMap.put("/**", "authc");

        //修改调整的登录页面
        shiroFilterFactoryBean.setLoginUrl("/loginpage");
        //设置未授权页面
        shiroFilterFactoryBean.setUnauthorizedUrl("/unAuth");

        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap);

        return shiroFilterFactoryBean;
    }
    @Bean
    public DefaultWebSecurityManager securityManager(@Qualifier("userRealm") UserRealm userRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(userRealm);
        return securityManager;
    }
    @Bean
    public UserRealm userRealm(){
        return new UserRealm();
    }
}
